package model.xml;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * XML encoding/decoding class
 * @author Sil
 *
 */
public class XMLCodec {

	private static XStream xstream=new XStream(new DomDriver());

	@SuppressWarnings("unchecked")
	private static void loadAliases(Map<String, Class> aliases){
		Iterator it = aliases.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry e = (Map.Entry)it.next();
			xstream.alias(e.getKey().toString(), e.getValue().getClass());
		}
	}

	@SuppressWarnings("unchecked")
	public static Object parseXml(Map<String, Class> aliases, String strRequest){
		loadAliases(aliases);
		return xstream.fromXML(strRequest);
	}

	@SuppressWarnings("unchecked")
	public static void toXML(Map<String, Class> aliases, Object obj, OutputStream out) throws IOException{
		loadAliases(aliases);
		out.write((xstream.toXML(obj).replaceAll("\n", "_barraN_").replaceAll("\r", "_barraR_")/*.replaceAll(" ", "")*/ + "\n").getBytes());
		out.flush();
	}
}
